package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryBrandService categoryBrandService;

    @Override
    public List<CategoryDTO> ofParent(Long pid) {
        List<Category> categories = query().eq("parent_id", pid).list();
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categories);
        return categoryDTOS;
    }

    @Override
    public CategoryDTO getCategoryPyId(Long id) {
        Category category = baseMapper.selectById(id);
        CategoryDTO categoryDTO = new CategoryDTO();
        BeanUtils.copyProperties(category, categoryDTO);
        return categoryDTO;
    }

    @Override
    public List<CategoryDTO> getCategoryPyIds(List<Long> ids) {
        List<Category> categories = new ArrayList<>();
        ids.stream().forEach((id)->{
            Category category = baseMapper.selectById(id);
            categories.add(category);
        });
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categories);
        return categoryDTOS;
    }

    @Override
    public List<CategoryDTO> getCategoryPyBrandId(Long bid) {

        //where brand_id
        List<CategoryDTO> list = new ArrayList<>();
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id",bid);
//        List<CategoryBrand> categoryBrandIds = categoryBrandService.query().eq("brand_id", bid).list();
        List<CategoryBrand> categoryBrandIds = categoryBrandService.list(queryWrapper);
//        List<Long> categoryIds= brands.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        for (CategoryBrand categoryBrandId : categoryBrandIds) {
            list.add(new CategoryDTO(this.getById(categoryBrandId.getCategoryId())));
        }
        return list;
    }



}